const base64 = require('base-64');
const CryptoJs = require('crypto-js');
const WebSocket = require('ws');

const requestObj = {
    APPID: '98362ce9',
    APISecret: 'NzZjMTVlMjNjOWE1OTRhODhlNmIyMDU1',
    APIKey: '6da465f6f5f0c43028724d5295ec2c18',
    Uid: "red润",
    sparkResult: ''
};

// 获取 WebSocket URL
const getWebsocketUrl = () => {
    return new Promise((resolve, reject) => {
        let url = "wss://spark-api.xf-yun.com/v1.1/chat";
        let host = "spark-api.xf-yun.com";
        let apiKeyName = "api_key";
        let date = new Date().toGMTString();
        let algorithm = "hmac-sha256";
        let headers = "host date request-line";
        let signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v1.1/chat HTTP/1.1`;
        let signatureSha = CryptoJs.HmacSHA256(signatureOrigin, requestObj.APISecret);
        let signature = CryptoJs.enc.Base64.stringify(signatureSha);

        let authorizationOrigin = `${apiKeyName}="${requestObj.APIKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;

        let authorization = base64.encode(authorizationOrigin);

        // 将空格编码
        url = `${url}?authorization=${authorization}&date=${encodeURI(date)}&host=${host}`;

        resolve(url);
    });
};

// 发送消息
const sendMessage = async (req, res) => {
    try {
        // 从请求体中获取输入内容
        const { inputVal } = req.body;
        if (!inputVal) {
            res.send("false");
            return;
        }
        console.log('inputVal:', inputVal);

        // 获取 WebSocket URL
        let myUrl = await getWebsocketUrl();

        // 创建 WebSocket 连接
        let socket = new WebSocket(myUrl);

        res.writeHead(200, {
            'Content-Type': 'application/json',
            'Transfer-Encoding': 'chunked'
        });

        socket.on('open', () => {
            console.log('连接开启！');

            let params = {
                "header": {
                    "app_id": requestObj.APPID,
                    "uid": requestObj.Uid
                },
                "parameter": {
                    "chat": {
                        "domain": "general",
                        "temperature": 0.5,
                        "max_tokens": 1024
                    }
                },
                "payload": {
                    "message": {
                        "text": [
                            { "role": "user", "content": inputVal }
                        ]
                    }
                }
            };

            console.log("发送消息");
            socket.send(JSON.stringify(params));
        });

        socket.on('message', (event) => {
            let data = JSON.parse(event);
            console.log("消息:", data);
            if (data.header.code !== 0) {
                console.log("出错了", data.header.code, ":", data.header.message);
                console.log("Datat", data.header.message.replace(/\n/g, '<br>').replace(/\t/g, '')+'<br/> 亲，文明一点。免费接口制作不易😈');

            res.write(JSON.stringify({ 
                "result": {
                    "header": {
                        "code": 0,
                        "message": "Success",
                        "sid": "cht000ba3e5@dx190429e9163b894540",
                        "status": 2
                    },
                    "payload": {
                        "choices": {
                            "status": 2,
                            "seq": 5,
                            "text": [
                                {
                                    "content": data.header.message.replace(/\n/g, '<br>').replace(/\t/g, '')+'<br/> 亲，文明一点。免费接口制作不易😈', // 将制表符替换为四个空格.replace('\n','<br/>').replace('\n','<br/>'),
                                    "role": "assistant",
                                    "index": 0
                                }
                            ]
                        },
                        "usage": {
                            "text": {
                                "question_tokens": 16,
                                "prompt_tokens": 16,
                                "completion_tokens": 33,
                                "total_tokens": 49
                            }
                        }
                    }
                }
            } ));

                socket.close();
            return
            }
            res.write(JSON.stringify({ result: data }));
            if (data.header.code === 0 && data.header.status === 2) {
                setTimeout(() => {
                    socket.close();
                }, 1000);
            }
        });

        socket.on('close', () => {
            console.log('连接关闭！');
            res.end();
        });

        socket.on('error', (error) => {
            console.log('连接错误！', error);
            res.status(500).json({ error: 'WebSocket connection error' });
        });
    } catch (error) {
        console.error('Error:', error);
        res.status(500).json({ error: 'Failed to send message' });
    }
};

module.exports = { sendMessage };
